package com.yyq.config;

import com.yyq.pojo.Configuration;
import com.yyq.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author yuanyueqiang
 * @Date 2021-11-27 22:07
 */
public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration){
        this.configuration = configuration;
    }

    /**
     * 解析mapper.xml
     */
    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        List<Element> selectList = rootElement.selectNodes("//select");
        List<Element> updateList = rootElement.selectNodes("//update");
        List<Element> deleteList = rootElement.selectNodes("//delete");
        List<Element> insertList = rootElement.selectNodes("//insert");
        selectList.addAll(updateList);
        selectList.addAll(deleteList);
        selectList.addAll(insertList);
        String namespace = rootElement.attributeValue("namespace");
        for (Element element : selectList) {
            MappedStatement mappedStatement = new MappedStatement();
            String id = element.attributeValue("id");
            String sql = element.getTextTrim();
            String parameterType = element.attributeValue("parameterType");
            String resultType = element.attributeValue("resultType");
            String queryType = element.getName();
            mappedStatement.setId(id);
            mappedStatement.setSql(sql);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setQueryType(queryType);
            configuration.getMappedStatementMap().put(namespace+"."+id,mappedStatement);
        }
    }
}
